package sskj.regulatory.presentation.screen.home

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.ListView
import android.widget.TextView
import com.bigkoo.convenientbanner.ConvenientBanner
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import com.vondear.rxtools.RxActivityTool
import com.vondear.rxtools.activity.ActivityScanerCode
import com.vondear.rxtools.interfaces.OnRxScanerListener
import com.vondear.rxtools.view.RxToast

import kotlinx.android.synthetic.main.fragment_home.view.*
import sskj.regulatory.R
import sskj.regulatory.domain.entity.MenuItemDescription
import sskj.regulatory.domain.entity.homesection.HomeSection
import sskj.regulatory.presentation.base.BaseRecyclerAdapter
import sskj.regulatory.presentation.base.RecyclerViewHolder
import sskj.regulatory.presentation.base_mvp.base.BaseFragment
import sskj.regulatory.presentation.screen.pmdust.PmDustFragment
import sskj.regulatory.presentation.screen.qrlogin.QrLoginFragment
import sskj.regulatory.presentation.screen.signature.signedlist.SignedMainFragment
import sskj.regulatory.presentation.screen.sitevideo.sitevmain.SiteVideoMainFragment
import javax.inject.Inject


class HomeFragment : BaseFragment<HomeContract.View, HomeContract.Presenter>(), HomeContract.View, OnRxScanerListener {


    private val TAG = "HomeFragment"

    @Inject
    lateinit var mPresenter: HomePresenter

    private lateinit var mItemAdapter: ItemAdapter

    private lateinit var mListAdapter: ListAdapter

    private lateinit var mBanner: ConvenientBanner<Int>

    private var images = ArrayList<Int>()

    private val menuItems: ArrayList<MenuItemDescription>
        get() {
            var menuItems = ArrayList<MenuItemDescription>()
            resources.getStringArray(R.array.menu).forEach {
                when (it) {
                    "电子签章" -> menuItems.add(MenuItemDescription(it, R.mipmap.ic_ca, SignedMainFragment::class))
                    "质量监督" -> menuItems.add(MenuItemDescription(it, R.mipmap.ic_zljd, SignedMainFragment::class))
                    "安全监督" -> menuItems.add(MenuItemDescription(it, R.mipmap.ic_aqjd, SignedMainFragment::class))
                    "工地视频" -> menuItems.add(MenuItemDescription(it, R.mipmap.ic_sp, SiteVideoMainFragment::class))
                    "扬尘监控" -> menuItems.add(MenuItemDescription(it, R.mipmap.ic_yc, PmDustFragment::class))
                }
            }
            return menuItems
        }

    override fun onBackPressed(): Boolean = true

    private var items = ArrayList<HomeSection>()

    override val layoutResId: Int = R.layout.fragment_home

    override fun initPresenter() = mPresenter

    override fun translucentFull(): Boolean = true

    override fun injectDependencies() {
        activityComponent.inject(this)
    }

    override fun initView() {
        initTopBar()
        initRecyclerView()
        initMyBanner()
        initListView()
    }

    override fun onFail(type: String?, message: String?) {
        RxToast.showToast(message)
    }

    override fun onSuccess(type: String?, result: com.google.zxing.Result?) {
        showLoading()
        mPresenter.qrLogin(result!!.text)

    }

    override fun showNoBingDingRole() {
        hideLoading()
        QMUIDialog.MessageDialogBuilder(getActivity())
                .setTitle("信息提示")
                .setMessage("没有该系统的用户,请先绑定用户后在扫码登录。")
                .addAction("确定") { dialog, _ ->
                    activity.tipDialog?.dismiss()
                    dialog.dismiss()
                }
                .create(R.style.QMUI_Dialog).show()
    }


    override fun gotoDoQrLogin(type: String, qrCode: String) {
        val qrLoginFragment = QrLoginFragment()
        qrLoginFragment.arguments = Bundle().apply {
            putString("type", type)
            putString("qrCode", qrCode)
        }
        startFragment(qrLoginFragment)
    }

    override fun showLoading() {
        activity.tipDialog = QMUITipDialog.Builder(context)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("正在加载")
                .create()
        activity.tipDialog?.show()
    }

    override fun hideLoading() {
        activity.tipDialog?.dismiss()
    }

    private fun initTopBar() {
        mCacheView.hTopBar.addLeftImageButton(R.mipmap.ic_scan, R.id.topbar_left_scan_button).setOnClickListener {
            ActivityScanerCode.setScanerListener(this)
            startActivity(Intent(getActivity(), ActivityScanerCode::class.java))
        }

        mCacheView.hTopBar.addLeftImageButton(R.mipmap.ic_search, R.id.topbar_left_search_button).setOnClickListener {

        }

        mCacheView.hTopBar.addRightImageButton(R.mipmap.ic_add, R.id.topbar_right_add_button).setOnClickListener {

        }

    }


    private fun initRecyclerView() {

        mItemAdapter = ItemAdapter(context, menuItems)

        mItemAdapter.setOnItemClickListener(object : BaseRecyclerAdapter.OnItemClickListener {
            override fun onItemClick(itemView: View, pos: Int) {
                startFragment(mItemAdapter.getItem(pos).mKitClass?.java?.newInstance())
            }
        })

        mCacheView.hRecyclerView.isNestedScrollingEnabled = false
        mCacheView.hRecyclerView.adapter = mItemAdapter
        val spanCount = 4
        mCacheView.hRecyclerView.layoutManager = GridLayoutManager(context, spanCount)
        //recyclerView.addItemDecoration(GridDividerItemDecoration(context, spanCount))
    }

    private fun initListView() {
        items.add(HomeSection("筑支付", "10元红包", "邀新人赚红包",
                R.mipmap.ic_launcher_round, "发红包赚赏金", "速瓜分10亿赏金", R.mipmap.ic_launcher))
        items.add(HomeSection("筑生活", "23元兑换券", "汉堡王",
                R.mipmap.ic_launcher_round, "九价疫苗来了", "最全hpv疫苗科普", R.mipmap.ic_launcher))
        mListAdapter = ListAdapter(items, context)
        mCacheView.test_list.adapter = mListAdapter
        setListViewHeightBasedOnChildren(mCacheView.test_list)
    }

    private fun initMyBanner() {
        images.add(R.mipmap.test1)
        images.add(R.mipmap.test2)
        images.add(R.mipmap.test3)
        //轮播图
        mBanner = mCacheView.findViewById(R.id.convenient_banner)
        mBanner
                .setPages({ BannerImageHolderView() }, images)
                //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                .setPageIndicator(intArrayOf(R.mipmap.ic_page_indicator, R.mipmap.ic_page_indicator_focused))
                //设置指示器的方向
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                //设置轮播时间间隔
                .startTurning(2000)
    }

    private fun setListViewHeightBasedOnChildren(listView: ListView) {
        // 获取ListView对应的Adapter
        val listAdapter = listView.getAdapter() ?: return

        var totalHeight = 0
        var i = 0
        val len = listAdapter.getCount()
        while (i < len) { // listAdapter.getCount()返回数据项的数目
            val listItem = listAdapter.getView(i, null, listView)
            listItem.measure(0, 0) // 计算子项View 的宽高
            totalHeight += listItem.getMeasuredHeight() + 15 // 统计所有子项的总高度
            i++
        }

        val params = listView.getLayoutParams()
        params.height = totalHeight + listView.getDividerHeight() * (listAdapter.getCount() - 1)
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.layoutParams = params
    }

    class ItemAdapter(ctx: Context?, data: List<MenuItemDescription>) : BaseRecyclerAdapter<MenuItemDescription>(ctx, data) {

        override fun getItemLayoutId(viewType: Int): Int {
            return R.layout.item_home_menu
        }

        override fun bindData(holder: RecyclerViewHolder, position: Int, item: MenuItemDescription) {
            holder.getTextView(R.id.itemName).text = item.name
            if (item.iconRes !== 0) {
                holder.getImageView(R.id.itemIcon).setImageResource(item.iconRes)
            }
        }
    }
    override fun showError(message: String?) {
        QMUIDialog.MessageDialogBuilder(getActivity())
                .setTitle("错误提示")
                .setMessage(message)
                .addAction("确定") { dialog, _ -> dialog.dismiss() }
                .create(R.style.QMUI_Dialog).show()
    }
    class ListAdapter(val list: ArrayList<HomeSection>, val context: Context?) : BaseAdapter() {
        override fun getCount(): Int {
            return list.size
        }

        override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? {
            var holder: TestViewHolder
            var v: View
            if (convertView == null) {
                v = View.inflate(context, R.layout.item_listview, null)
                holder = TestViewHolder(v)
                v.tag = holder
            } else {
                v = convertView
                holder = v.tag as TestViewHolder
            }
            holder.sectionName.text = list[position].sectionName
            holder.leftTitle.text = list[position].leftTitle
            holder.leftDesc.text = list[position].leftDesc
            holder.leftpicurl.setImageResource(list[position].leftpicurl)
            holder.rightTitle.text = list[position].rightTitle
            holder.rightDesc.text = list[position].rightDesc
            holder.rightpicurl.setImageResource(list[position].rightpicurl)
            return v
        }

        override fun getItem(position: Int): Any? {
            return list.get(position)
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }
    }

    class TestViewHolder(viewItem: View) {
        var sectionName: TextView = viewItem.findViewById(R.id.item_sectionName)
        var leftTitle: TextView = viewItem.findViewById(R.id.item_leftTitle)
        var leftDesc: TextView = viewItem.findViewById(R.id.item_leftDesc)
        var leftpicurl: ImageView = viewItem.findViewById(R.id.item_leftpicurl)
        var rightTitle: TextView = viewItem.findViewById(R.id.item_rightTitle)
        var rightDesc: TextView = viewItem.findViewById(R.id.item_rightDesc)
        var rightpicurl: ImageView = viewItem.findViewById(R.id.item_rightpicurl)
    }
}